<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-责任人员配置`"
			width="1000px"
			:show-content-loading="showLoading"
			:confirm-btn-loading="confirmBtnLoading"
			:show-confirm-btn="pageType !== 'detail'"
			:show-cancel-btn="pageType !== 'detail'"
			:show-close-btn="pageType === 'detail'"
			@on-close="onVisibleChange(false)"
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail'" label-width="120px" :show-message="false">
				<div ref="box1">
					<el-tag type="primary" effect="plain" class="margin-bottom-4">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<jk-card>
						<el-row class="flex-start-center-wrap">
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="人员" prop="empId">
									<span v-if="pageType === 'detail' || dataId" class="read-only-2">{{ ruleForm.empName }}</span>
									<remote-search-emp-input
										v-else
										placeholder="计划员"
										only-key="empId"
										query-name="empName"
										:form-data="ruleForm"
										@on-select="onSelectEmpChange"
									></remote-search-emp-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="关联用户">
									<span class="read-only-2">{{ ruleForm.userInfo && ruleForm.userInfo.username ? ruleForm.userInfo.username : '无' }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item class="margin-bottom-10" label="用户授权工序">
									<span class="read-only-2">{{ ruleForm.userInfo && ruleForm.userInfo.processList && ruleForm.userInfo.processList.length ? ruleForm.userInfo.processList.map(x => x.processName).join() : '无' }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="责任类别" prop="dutyState">
									<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.dutyState === 0 ? '保养' : '巡检' }}</span>
									<jk-select
										v-else
										v-model="ruleForm.dutyState"
										:clearable="true"
										:option-list="dutyStateList"
										placeholder="责任类别"
										size="medium"
										@change="onDutyStateChange"
									></jk-select>
								</el-form-item>
							</el-col>
							<el-col
								:span="
									24"
							>
								<el-form-item v-if="ruleForm.dutyState === 0 || ruleForm.dutyState === null" class="margin-bottom-0" label="保养类别" prop="upkeepTypeIds">
									<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.upkeepTypeList ? ruleForm.upkeepTypeList.map(x => x.name).join() : '' }}</span>
									<jk-select v-else v-model="ruleForm.upkeepTypeIds" multiple :option-list="upkeepTypeList" size="medium" class="width-100-percent" placeholder="保养类别(多)"></jk-select>
								</el-form-item>
								<!--								<el-form-item v-if="dutyStateData[0] === 0 || dutyStateData[1] === 0" class="margin-bottom-0" label="保养类别" prop="upkeepTypeIds">-->
								<!--									<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.upkeepTypeList ? ruleForm.upkeepTypeList.map(x => x.name).join() : '' }}</span>-->
								<!--									<jk-select v-else v-model="ruleForm.upkeepTypeIds" multiple :option-list="upkeepTypeList" size="medium" class="width-100-percent" placeholder="保养类别(多)"></jk-select>-->
								<!--								</el-form-item>-->
							</el-col>
						</el-row>
					</jk-card>
				</div>
				<div ref="box2" class="margin-bottom-4 margin-top-10 flex-between-center">
					<div class="flex-start-center" style="font-size: 13px;align-items: flex-end;">
						<jk-button
							v-if="pageType !== 'detail'"
							icon="el-icon-plus"
							size="mini"
							class=""
							type="primary"
							:disabled="!ruleForm.empId || !ruleForm.userInfo || !ruleForm.userInfo.processList.length"
							@click="onAddBtn"
						>保养项目</jk-button>
						<el-tag v-else type="primary" effect="plain" class="">
							<span class="el-icon-tickets item-gap"></span>
							<span>保养项目</span>
						</el-tag>
						<span>(共: {{ ruleForm.machineList ? ruleForm.machineList.length : 0 }}台)</span>
					</div>
					<div>
						<jk-button
							size="mini"
							icon="el-icon-delete"
							type="danger"
							plain
							@click="onClearAllBtn"
						>清空</jk-button>
					</div>
				</div>
				<jk-table border :data="ruleForm.machineList || []" :height="dialogTableHeight - 20">
					<vxe-column title="机台名称" align="left" field="machineName" :width="110" />
					<vxe-column title="机型" align="left" field="machineModelName" :min-width="100" />
					<vxe-column title="工序" align="left" field="processName" :min-width="100" />
					<vxe-column title="操作" align="center" field="operation" :width="100">
						<template slot-scope="scope">
							<div class="flex-center"><jk-button size="mini" icon="el-icon-minus" @click="onDeleteBtn(scope.rowIndex)"></jk-button></div>
						</template>
					</vxe-column>
				</jk-table>
			</el-form>
		</jk-dialog>
		<select-machine-dialog
			:default-process-list="ruleForm.userInfo && ruleForm.userInfo.processList ? ruleForm.userInfo.processList : []"
			check-key-name="machineId"
			:checked-data="ruleForm.machineList || []"
			:dialog-state="selectMachineDialogState"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
		></select-machine-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { machineManagerUpkeepTypePage } from '../../../../api/machine/upkeepCategory';
    import remoteSearchEmpInput from '../../../production/order/components/remote-search-emp-input';
    import { validateArr } from '../../../../utils/jk/validator';
    import selectMachineDialog from './components/select-machine-dialog';
    import {
        machineManagerUpkeepPersonnelCreate, machineManagerUpkeepPersonnelGet,
        machineManagerUpkeepPersonnelUpdate
    } from '../../../../api/machine/upkeepEmp';
    import { systemUserGetUserInfoAndProcessByEmpId } from '../../../../api/machine/upkeepOrder';
    export default {
        components: {
            selectMachineDialog,
            remoteSearchEmpInput
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            pageType: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                selectMachineDialogState: false,
                upkeepTypeList: [],
                processList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                dutyStateList: [
                    { id: 0, name: '保养', code: 'BY' },
                    { id: 1, name: '巡检', code: 'XJ' }
                ],
                ruleForm: {
                    id: null,
                    empId: null,
                    dutyState: null,
                    empNode: '',
                    empName: '',
                    upkeepTypeIds: [],
                    upkeepTypeList: [],
                    machineList: [],
                    remark: '',
                    userInfo: {
                        username: '',
                        processList: []
                    }
                },
                rules: {
                    empId: [{ required: true, trigger: 'change' }],
                    dutyState: [{ required: true, trigger: 'change' }],
                    upkeepTypeIds: [{ required: true, validator: validateArr, trigger: 'blur' }]
                },
                dutyStateData: []
            };
        },
        methods: {
            onDutyStateChange(dutyState) {
                this.ruleForm.machineList = [];
                // this.dutyStateData = dutyState;
            },
            onClearAllBtn() {
                this.$set(this.ruleForm, 'machineList', []);
            },
            onDeleteBtn(rowIndex) {
                this.ruleForm.machineList.splice(rowIndex, 1);
            },
            onAddBtn() {
                this.selectMachineDialogState = true;
            },
            onConfirmBtnOfSelectMachineDialog(arr = []) {
                arr.forEach(x => {
                    this.ruleForm.machineList.push({
                        machineId: x.id,
                        machineCode: x.code,
                        machineName: x.name,
                        processId: x.processId,
                        processCode: x.processCode,
                        processName: x.processName,
                        workshopId: x.workshopId,
                        workshopCode: x.workshopCode,
                        workshopName: x.workshopName,
                        machineModelId: x.machineModelId,
                        machineModelCode: x.machineModelCode,
                        machineModelName: x.machineModelName
                    });
                });
                this.selectMachineDialogState = false;
            },
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'empId', e.id);
                    this.$set(this.ruleForm, 'empCode', e.code);
                    this.$set(this.ruleForm, 'empName', e.name);
                    this.getUserDataPermissionInfo();
                }
            },
            getUserDataPermissionInfo() {
                if (!this.ruleForm.empId) return;
                systemUserGetUserInfoAndProcessByEmpId({
                    empId: this.ruleForm.empId
                }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        const userInfo = {
                            username: resData.username,
                            processList: resData.processList.map(x => {
                                return {
                                    processId: x.processId,
                                    processCode: x.processCode,
                                    processName: x.processName
                                };
                            })
                        };
                        this.$set(this.ruleForm, 'userInfo', userInfo);
                    }
                });
            },
            onBlurCode(e) {
                this.$set(this.ruleForm, 'code', this.ruleForm.code ? this.ruleForm.code.toUpperCase() : '');
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));

                const upkeepTypeItem = this.upkeepTypeList.find(x => x.id === params.upkeepTypeId) || {};
                params.upkeepTypeCode = upkeepTypeItem.code;
                params.upkeepTypeName = upkeepTypeItem.name;
                params.upkeepTypeList = params.upkeepTypeIds ? this.upkeepTypeList.filter(x => params.upkeepTypeIds.includes(x.id)) : [];
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        const api = !this.dataId ? machineManagerUpkeepPersonnelCreate : machineManagerUpkeepPersonnelUpdate;
                        this.confirmBtnLoading = true;
                        api(this.getParamData()).then(res => {
                            this.confirmBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$tipsBar(this, 'save');
                                this.$emit('on-finish');
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machineManagerUpkeepPersonnelGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.upkeepTypeIds = resData.upkeepTypeList ? resData.upkeepTypeList.map(x => x.id) : [];
                        this.ruleForm = resData;
                    }
                });
            },
            getUpkeepTypeListRequest() {
                return machineManagerUpkeepTypePage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.upkeepTypeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getUpkeepTypeListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
